package com.xiweicheng.test.springcloud.ms.c;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@RestController
@EnableDiscoveryClient
@Slf4j
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    Environment env;

    @Autowired
    DiscoveryClient client;

    @Autowired
    Registration registration;

    @GetMapping("hello")
    public String hello(@RequestParam(value = "sleep", defaultValue = "0") int sleep) {

        log.debug("sleepTime: {}", sleep);

        try {
            if (sleep != 0) {
                Thread.sleep(sleep);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.warn(e.getMessage(), e);
        }

        String val = "hello, i am service: " + env.getProperty("spring.application.name") + ", on port:"
                + env.getProperty("server.port") + ", service id: " + registration.getServiceId() + ", sleep time: "
                + sleep;

        log.debug(val);

        return val;
    }
}
